package com.boilermaker.lotterysystem.service.impl;

import cn.hutool.core.date.DateUtil;
import com.boilermaker.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.boilermaker.lotterysystem.common.exception.ServiceException;
import com.boilermaker.lotterysystem.common.utils.CaptchaUtil;
import com.boilermaker.lotterysystem.common.utils.MailUtil;
import com.boilermaker.lotterysystem.common.utils.RedisUtil;
import com.boilermaker.lotterysystem.common.utils.RegexUtil;
import com.boilermaker.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 验证码服务实现类
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private static final String REDIS_VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";

    private static final Long REDIS_VERIFICATION_CODE_TTL = 60L;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private MailUtil mailUtil;

    /**
     * 发送并缓存验证码
     */
    @Override
    public void sendVerificationCode(String mail) {
        if (mail == null) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_IS_EMPTY);
        }

        if (!RegexUtil.checkMail(mail)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_PATTERN_ERROR);
        }

        // 生成验证码
        String captcha = CaptchaUtil.getCaptcha(4);

        // 向用户发送验证码
        String subject = "【LotterySystem】登录通知";
        String context = "您的验证码为：" + captcha + "，该验证码 1 分钟内有效。";
        mailUtil.sendSampleMail(mail, subject, context);

        // 缓存验证码
        redisUtil.set(REDIS_VERIFICATION_CODE_PREFIX + mail,
                captcha, REDIS_VERIFICATION_CODE_TTL);
    }

    /**
     * 从缓存中获取验证码
     */
    @Override
    public String getVerificationCode(String mail) {
        if (!RegexUtil.checkMail(mail)) {
            throw new ServiceException(ServiceErrorCodeConstants.MAIL_PATTERN_ERROR);
        }

        return redisUtil.get(REDIS_VERIFICATION_CODE_PREFIX + mail);
    }
}
